<?php

include_once dirname(__FILE__).'/SimpleRecord.class.php';

define('DEFAULT_TEMPLATE_INDEX', dirname(__FILE__).'/template/index.default.html');
define('DEFAULT_TEMPLATE_EDIT', dirname(__FILE__).'/template/edit.default.html');

define('DEFAULT_DB', dirname(__FILE__).'/db/'.basename($_SERVER['SCRIPT_NAME']));

define('PATH_DEFAULT_FORMATTER', dirname(__FILE__).'/formatters/markdown.php');
define('DEFAULT_FORMATTER', 'Markdown');

class SimpleRecordController {
	var $title;
	var $indexTemplate;
	var $editTemplate;
	var $record;

	function SimpleRecordController(
		$title,
		$indexTemplate = DEFAULT_TEMPLATE_INDEX,
		$editTemplate = DEFAULT_TEMPLATE_EDIT,
		$db = DEFAULT_DB,
		$formatter = null
	) {
		$this->title = $title;
		$this->indexTemplate = $indexTemplate;
		$this->editTemplate = $editTemplate;
		$this->record = new SimpleRecord($db);

		if($formatter == null) {
			if(PATH_DEFAULT_FORMATTER != null and is_file(PATH_DEFAULT_FORMATTER))
				include_once PATH_DEFAULT_FORMATTER;

			$formatter = DEFAULT_FORMATTER;
		}

		$this->formatter = $formatter;

		# fucking <magic_quotes_gpc>
		if(get_magic_quotes_gpc()) {
			$GLOBALS['_GET'] = array_map('stripslashes', $_GET);
			$GLOBALS['_POST'] = array_map('stripslashes', $_POST);
			$GLOBALS['_COOKIE'] = array_map('stripslashes', $_COOKIE);
		}

		header('Content-Type: text/html; charset=UTF-8');
	}

	function accessToTemplateResource($inner_path) {
		if($_SERVER['HTTP_REFERER'] != null) {
			$parsed_url = parse_url($_SERVER['HTTP_REFERER']);

			if(in_array('edit', explode('&', $parsed_url['query'])))
				$path_to_load = dirname($this->editTemplate).$inner_path;
		}
		
		if(!isset($path_to_load))
			$path_to_load = dirname($this->indexTemplate).$inner_path;

		if(!is_readable($path_to_load)) {
			trigger_error('No template resource file: '.$inner_path, E_USER_ERROR);
			return false;
		}

		$image_exts = array('.jpg', '.png', '.gif', '.jpeg', '.bmp', '.swf');

		if(strtolower(substr($path_to_load, -4)) == '.css')
			$content_type = 'text/css; charset=UTF-8';
		else if(strtolower(substr($path_to_load, -3)) == '.js')
			$content_type = 'text/javascript; charset=UTF-8';
		else if(in_array($image_exts, strtolower(substr($path_to_load, -4))))
			$content_type = image_type_to_mime_type(exif_imagetype($path_to_load));

		ob_clean();

		if(isset($content_type))
			@header('Content-Type: '.$content_type);

		return include $path_to_load;
	}

	function index($index = '') {
		$index = $index == '' ? null : (int) $index;
		$formatter = $this->formatter;
		$page = $this->record->get($index);
		$pageContent = $page ? $page->getContent() : '';
		$pageContentFormatted = call_user_func($formatter, $pageContent);
		$path = basename($_SERVER['SCRIPT_NAME']).'/';

		include $this->indexTemplate;
		return $pageContent;
	}

	function edit() {
		$page = $this->record->get();
		$pageContent = $page ? $page->getContent() : '';
		$locked = $this->record->isLocked();
		$readonly = $locked ? ' readonly="readonly"' : '';
		$disabled = $locked ? ' disabled="disabled"' : '';
		$path = basename($_SERVER['SCRIPT_NAME']).'/';

		include $this->editTemplate;
		return $pageContent;
	}

	function set($content) {
		$this->record->set($content);
		$this->index();
		return $content;
	}

	function lock() {
		header('Content-Type: text/plain; charset=UTF-8');
		echo date('D M j Y H:i:s \G\M\TO', $this->record->lock());
	}

	function unlock() {
		$this->record->unlock();
	}

	function isLocked() {
		if($is_locked = $this->record->isLocked())
			echo date('D M j Y H:i:s \G\M\TO', $is_locked);
	}

	function preview() {
		echo call_user_func($this->formatter, $_POST['content']);
	}

	function route() {
		# file/abc.file    <==> template_dir/abc.file
		# in order to access to template resources
		# ex) css, javascript, images...

		if(strlen($_SERVER['PHP_SELF']) > strlen($_SERVER['SCRIPT_NAME'])) {
			$inner_path = substr($_SERVER['PHP_SELF'], strlen($_SERVER['SCRIPT_NAME']));
	
			while(strpos($inner_path, '/../') !== false)
				$inner_path = str_replace('/../', '/', $inner_path);

			if($inner_path != '/' and strlen($inner_path) > 0)
				return $this->accessToTemplateResource($inner_path);
		}

		# file, file?      <==> $this->index()
		# file?123         <==> $this->index(123)
		# file?method      <==> $this->method()
		# file?method&1&2  <==> $this->method(1, 2)

		$parameters = array_map('urldecode', explode('&', $_SERVER['QUERY_STRING']));
		$action = array_shift($parameters);

		if(strlen(trim($action)) < 1 and $_POST['content'] != '')
			return $this->set($_POST['content']);
		else if(is_numeric($action) or strlen(trim($action)) < 1)
			return $this->index($action);
		else if(method_exists($this, $action))
			return call_user_method($action, $this, $parameters);

		trigger_error('Undefined action: '.$action, E_USER_ERROR);
		return false;
	}
}

?>